package com.thon.service.topic;

import com.thon.commons.persistence.Page;
import com.thon.dao.topic.ChoiceDao;
import com.thon.entity.topic.Choice;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Chen on 2016/2/18.
 */
@Service
@Transactional
public class ChoiceService {
    
    @Autowired
    private ChoiceDao choiceDao;

    public Choice getChoice(int id){
        return choiceDao.get(id);
    }

    public void saveChoice(Choice Choice){
        choiceDao.save(Choice);
    }

    public void delChoice(Choice Choice){
        choiceDao.delete(Choice);
    }

    public Page<Choice> findChoices(Page<Choice> page, Choice choice) {
        DetachedCriteria dc = choiceDao.createDetachedCriteria();
        if(choice.getStudent()!= null){
            dc.add(Restrictions.eq("student.id", choice.getStudent().getId()));
        }
        if (choice.getTopic() != null ) {
            dc.createAlias("topic", "topic");
            if (choice.getTopic().getDirectTeacher() != null) {
                dc.createAlias("topic.directTeacher", "d");
                if (choice.getTopic().getDirectTeacher().getId() != null) {
                    dc.add(Restrictions.eq("topic.directTeacher.id", choice.getTopic().getDirectTeacher().getId()));
                }
            }
        }
        if (choice.getDelFlag() == 0) {
            Integer[] del = {0,1};
            dc.add(Restrictions.in("delFlag", del));
        }
        if (choice.getDelFlag() == 1) {
            dc.add(Restrictions.eq("delFlag", 0));
        }
        dc.addOrder(Order.desc("id"));

        return choiceDao.find(page, dc);
    }

    public Boolean ifChoice(Integer id) {
        List<Choice> choiceList = choiceDao.ifChoice(id);
        if(choiceList.size() == 0){
            return true;
        }else{
            return false;
        }
    }
}
